/**
 * Created by bootdo.
 */
import axios from 'axios'
import qs from 'qs'
//进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import promise from 'es6-promise'
import vuex from '../store'
import { showLoading, hideLoading } from '../loading';
import comm from '../service/comm'
require('es6-promise').polyfill()
promise.polyfill() // 兼容 Promise

axios.defaults.withCredentials = true;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //配置请求头
import {
    bus
} from '../bus.js'
let time = null;
let code = null;
axios.interceptors.request.use(
    config => {
        //请求头需要带token
        // vuex.commit('showLoading', true);
        // showLoading();
        // instanceof File
        // let flag = true
        // if (Object.keys(config.data).length) {
        //     for (let key in config.data) {
        //         let value = config.data[key] instanceof File ? '' : JSON.stringify(config.data[key])
        //         if (value) {
        //             if ((value.indexOf('*') != -1) || (value.indexOf('%') != -1)) {
        //                 comm.showMsg(false, '检测到你输入的数据，含有数据库非法词汇，本次操作将被拦截，请检测是否含有"*"，"%"')
        //                     // flag = false
        //             }
        //         }
        //     }
        // }
        // if (!flag) {
        //     setTimeout(() => {
        //         let loading = document.querySelector('.el-loading-mask')
        //         loading.style.display = 'none'
        //     }, 100)
        //     return
        // }

        if (window.sessionStorage.getItem('token')) {
            config.headers['token'] = window.sessionStorage.getItem('token');
            config.headers['lang'] = window.localStorage.getItem('lang') || 'zh_CN'
        }
        NProgress.start()
        return config
    },
    error => {
        return Promise.reject(error)
    }
);
// 添加一个响应拦截器
axios.interceptors.response.use(function(response) {
    // hideLoading();
    // vuex.commit('showLoading', false);
    // console.log(response, 'response');
    if (response.data && response.data.code && response.data.code == '403') {
        console.log('token失效');
        bus.$emit('test', 'token失效')
        return;
    }
    // if (response.data && response.data == 'error') {
    //     return;
    // }
    NProgress.done()
    return response;
}, function(error) {

    // Do something with response error
    return Promise.reject(error);
});

//基地址 1:国内 0：国外
let base = process.env.VUE_APP_BASE_API2
    // process.env.VUE_APP_BASE_API2
    // if (window.location.host.indexOf('eu')) {
    //     base = '/phoebus'
    // } else {
    //     process.env.VUE_APP_BASE_API2
    // }
    //通用方法
export const POST = (url, params) => {
    url = url.split('.')[0]
    return axios.post(`${base}${url}`, params).then(res => res.data)
}

export const POST4 = (url, params) => {
    url = url.split('.')[0]
    return new Promise((resolve, reject) => {
        axios.post(`/proxyApp${url}`, params,
            // 将axios 对象obj数据的post请求转化为formdata格式
            {
                transformRequest: [function(data) {
                    var str = [];
                    for (var p in data) {
                        str.push(p + "=" + data[p]);
                    }
                    return str.join("&");
                }],
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                    // 'token': sessionStorage.getItem('token') || ''
                },
                timeout: 800000
            }
        ).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}
export const POST7 = (url, params) => {
    // url = url.split('.')[0]
    return new Promise((resolve, reject) => {
        axios.post(`${url}`, params,
            // 将axios 对象obj数据的post请求转化为formdata格式
            {
                transformRequest: [function(data) {
                    var str = [];
                    for (var p in data) {
                        str.push(p + "=" + data[p]);
                    }
                    return str.join("&");
                }],
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                    // 'token': sessionStorage.getItem('token') || ''
                },
                timeout: 800000
            }
        ).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}

//通用方法
export const POST2 = (url, params) => {
        url = url.split('.')[0]
        return new Promise((resolve, reject) => {
            axios.post(`${base}${url}`, params,
                // 将axios 对象obj数据的post请求转化为formdata格式
                {
                    transformRequest: [function(data) {
                        var str = [];
                        for (var p in data) {
                            str.push(encodeURIComponent(p) + "=" + (data[p] === null || data[p] === undefined ? '' : encodeURIComponent(data[p])));
                        }
                        return str.join("&");
                    }],
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                    },
                    timeout: 800000
                }
            ).then(res => {
                resolve(res.data);
            }).catch((error) => {
                reject(error)
            })
        })
    }
    //模仿jq发送的post请求
export const POST6 = (url, params) => {
    url = url.split('.')[0]
    return new Promise((resolve, reject) => {
        axios.post(`${base}${url}`, qs.stringify(params, { indices: false }), {
            // transformRequest: [function(data) {
            //     let formData = new FormData();
            //     for (var p in data) {
            //         formData.append(p, data[p]);
            //     }
            //     return formData;
            // }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            timeout: 800000
        }).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}

//调用第三方接口
export const GET_OUT = (url, params) => {
    return new Promise((resolve, reject) => {
        axios.get(`${url}`, qs.stringify(params, { indices: false }), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            timeout: 800000
        }).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}

//上传文件调用
export const POST3 = (url, params) => {
    url = url.split('.')[0]
    return new Promise((resolve, reject) => {
        axios.post(`${base}${url}`, params,
            // 将axios 对象obj数据的post请求转化为formdata格式
            {
                transformRequest: [function(data) {
                    let formData = new FormData();
                    for (var p in data) {
                        //把特殊字符进行转码，文件类型的不需要转码
                        formData.append(p, data[p] instanceof File ? data[p] : data[p] === null ? '' : data[p]);
                    }
                    return formData;
                }],
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                timeout: 800000
            }
        ).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}
export const POST5 = (url, params) => {
    url = url.split('.')[0]
    return new Promise((resolve, reject) => {
        axios.post(`${base}${url}`, params,
            // 将axios 对象obj数据的post请求转化为formdata格式
            {
                transformRequest: [function(data) {
                    let formData = new FormData();
                    for (var p in data) {
                        //把特殊字符进行转码，文件类型的不需要转码
                        formData.append(p, data[p] === null ? '' : data[p]);
                    }
                    return formData;
                }],
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                },
                timeout: 800000
            }
        ).then(res => {
            resolve(res.data);
        }).catch((error) => {
            reject(error)
        })
    })
}


export const GET = (url, params) => {
    url = url.split('.')[0]
    return axios.get(`${base}${url}`, {
        params: params
    }).then(res => res.data)
}

export const PUT = (url, params) => {
    return axios.put(`${base}${url}`, params).then(res => res.data)
}

export const DELETE = (url, params) => {
    return axios.delete(`${base}${url}`, {
        params: params
    }).then(res => res.data)
}

export const PATCH = (url, params) => {
    return axios.patch(`${base}${url}`, params).then(res => res.data)
}
export const FILEUPLOAD = (url) => {
        return `${base}${url}`;
    }
    //不带进度条的
export const uploadFile2 = (url, params) => {
        return axios.post(`${base}${url}`, params, { headers: { 'Content-Type': 'Multipart/form-data' } }).then(res => res.data)
    }
    //带进度条的
export const uploadFile3 = (url, params, rogress) => {
    return axios.post(`${base}${url}`, params, {
        headers: { 'Content-Type': 'Multipart/form-data' },
        onUploadProgress: rogress.onUploadProgress,
        timeout: 1000 * 60 * 10
    }).then(res => res.data)
}
export const downloadFile = (url, params) => {
    window.location.href = `${base}${url}?list=${params}`;
}

//jsonp
axios.jsonp = (url, data) => {
    if (!url)
        throw new Error('url is necessary')
    const callback = 'CALLBACK' + Math.random().toString().substr(9, 18)
    const JSONP = document.createElement('script')
    JSONP.setAttribute('type', 'text/javascript')

    const headEle = document.getElementsByTagName('head')[0]

    let ret = '';
    if (data) {
        if (typeof data === 'string')
            ret = '&' + data;
        else if (typeof data === 'object') {
            for (let key in data)
                ret += '&' + key + '=' + encodeURIComponent(data[key]);
        }
        ret += '&_time=' + Date.now();
    }
    JSONP.src = `${url}?callback=${callback}${ret}`;
    return new Promise((resolve, reject) => {
        window[callback] = r => {
            resolve(r)
            headEle.removeChild(JSONP)
            delete window[callback]
        }
        headEle.appendChild(JSONP)
    })

}

export const JSONP = (url, params) => {
    console.log(url)
    return axios.jsonp(url, params)
        .then(res => console.log(res))
        .catch(err => console.log(err))
}